package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.papercutting.platform.entity.UserLike;
import com.papercutting.platform.repository.UserLikeRepository;
import com.papercutting.platform.service.UserLikeService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户点赞服务实现类
 */
@Service
public class UserLikeServiceImpl implements UserLikeService {
    
    private final UserLikeRepository userLikeRepository;
    
    public UserLikeServiceImpl(UserLikeRepository userLikeRepository) {
        this.userLikeRepository = userLikeRepository;
    }
    
    @Override
    public UserLike save(UserLike userLike) {
        if (userLike.getId() == null) {
            userLikeRepository.insert(userLike);
        } else {
            userLikeRepository.updateById(userLike);
        }
        return userLike;
    }
    
    @Override
    public UserLike findById(Long id) {
        return userLikeRepository.selectById(id);
    }
    
    @Override
    public List<UserLike> findAll() {
        return userLikeRepository.selectList(null);
    }
    
    @Override
    public Page<UserLike> findAll(Pageable pageable) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> page =
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                pageable.getPageNumber() + 1, pageable.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> result =
            userLikeRepository.selectPage(page, null);
        return new PageImpl<>(result.getRecords(), pageable, result.getTotal());
    }
    
    @Override
    public void deleteById(Long id) {
        userLikeRepository.deleteById(id);
    }
    
    @Override
    public List<UserLike> findByUserId(Long userId) {
        QueryWrapper<UserLike> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userLikeRepository.selectList(wrapper);
    }

    @Override
    public List<UserLike> findByTargetTypeAndTargetId(String targetType, Long targetId) {
        QueryWrapper<UserLike> wrapper = new QueryWrapper<>();
        wrapper.eq("target_type", targetType).eq("target_id", targetId);
        return userLikeRepository.selectList(wrapper);
    }

    @Override
    public UserLike findByUserIdAndTargetTypeAndTargetId(Long userId, String targetType, Long targetId) {
        QueryWrapper<UserLike> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("target_type", targetType)
               .eq("target_id", targetId)
               .eq("deleted", false); // 明确排除逻辑删除的记录
        return userLikeRepository.selectOne(wrapper);
    }

    @Override
    public List<UserLike> findByUserIdAndTargetType(Long userId, String targetType) {
        QueryWrapper<UserLike> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("target_type", targetType);
        return userLikeRepository.selectList(wrapper);
    }
    
    @Override
    @org.springframework.transaction.annotation.Transactional
    public boolean toggleLike(Long userId, String targetType, Long targetId) {
        org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
        logger.info("=== 开始执行toggleLike ===");
        logger.info("参数: userId={}, targetType={}, targetId={}", userId, targetType, targetId);
        
        try {
            // 查询当前点赞状态（确保排除逻辑删除的记录）
            UserLike existingLike = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
            boolean currentlyLiked = existingLike != null;
            logger.info("当前点赞状态: {}", currentlyLiked ? "已点赞(ID=" + (existingLike != null ? existingLike.getId() : "null") + ")" : "未点赞");
            
            if (currentlyLiked && existingLike != null) {
                // 当前已点赞 -> 执行取消点赞
                logger.info("当前已点赞，执行取消点赞逻辑...");
                
                try {
                    userLikeRepository.deleteById(existingLike.getId());
                    logger.info("成功删除点赞记录ID: {}", existingLike.getId());
                    
                    // 验证删除是否成功
                    UserLike verifyLike = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
                    boolean deleteSuccess = verifyLike == null;
                    logger.info("删除验证结果: {}", deleteSuccess ? "删除成功" : "删除失败");
                    
                    // 返回取消点赞后的状态：false（未点赞）
                    logger.info("=== 返回 false（取消点赞成功） ===");
                    return false;
                    
                } catch (Exception deleteEx) {
                    logger.error("删除点赞记录失败: ", deleteEx);
                    // 删除失败，返回原状态（仍然点赞）
                    logger.info("=== 删除失败，返回 true（仍然点赞） ===");
                    return true;
                }
                
            } else {
                // 当前未点赞 -> 执行点赞
                logger.info("当前未点赞，执行点赞逻辑...");
                
                try {
                    // 首先检查是否存在已删除的记录（使用原生SQL忽略逻辑删除）
                    UserLike deletedLike = userLikeRepository.findDeletedRecord(userId, targetType, targetId);
                    
                    if (deletedLike != null) {
                        // 恢复已删除的记录
                        logger.info("找到已删除的记录，恢复记录ID: {}", deletedLike.getId());
                        int restoreResult = userLikeRepository.restoreRecord(deletedLike.getId());
                        if (restoreResult > 0) {
                            logger.info("成功恢复点赞记录，ID: {}", deletedLike.getId());
                        } else {
                            logger.warn("恢复记录失败，ID: {}", deletedLike.getId());
                        }
                    } else {
                        // 没有已删除的记录，插入新记录
                        logger.info("没有已删除记录，插入新点赞记录");
                        UserLike newLike = new UserLike();
                        newLike.setUserId(userId);
                        newLike.setTargetType(targetType);
                        newLike.setTargetId(targetId);
                        
                        userLikeRepository.insert(newLike);
                        logger.info("成功插入新点赞记录，ID: {}", newLike.getId());
                    }
                    
                    // 验证操作是否成功
                    UserLike verifyLike = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
                    boolean operationSuccess = verifyLike != null;
                    logger.info("点赞操作验证结果: {}", operationSuccess ? "点赞成功" : "点赞失败");
                    
                    // 返回点赞后的状态：true（已点赞）
                    logger.info("=== 返回 true（点赞成功） ===");
                    return true;
                    
                } catch (Exception insertEx) {
                    logger.error("点赞操作失败: ", insertEx);
                    
                    // 检查是否是唯一索引冲突错误
                    if (insertEx.getMessage() != null && insertEx.getMessage().contains("Duplicate entry")) {
                        logger.warn("检测到重复记录错误，尝试恢复已删除记录...");
                        try {
                            // 再次尝试恢复已删除记录（使用原生SQL）
                            UserLike retryDeletedLike = userLikeRepository.findDeletedRecord(userId, targetType, targetId);
                            
                            if (retryDeletedLike != null) {
                                int retryRestoreResult = userLikeRepository.restoreRecord(retryDeletedLike.getId());
                                if (retryRestoreResult > 0) {
                                    logger.info("重试恢复成功，记录ID: {}", retryDeletedLike.getId());
                                    return true;
                                } else {
                                    logger.warn("重试恢复失败，记录ID: {}", retryDeletedLike.getId());
                                }
                            } else {
                                logger.warn("重试时未找到已删除记录");
                            }
                        } catch (Exception retryEx) {
                            logger.error("重试恢复失败: ", retryEx);
                        }
                    }
                    
                    // 操作失败，返回原状态（仍未点赞）
                    logger.info("=== 点赞操作失败，返回 false（仍未点赞） ===");
                    return false;
                }
            }
            
        } catch (Exception e) {
            logger.error("toggleLike 执行异常: ", e);
            
            // 异常时返回原状态，避免状态混乱
            UserLike currentLike = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
            boolean currentStatus = currentLike != null;
            logger.info("异常处理，返回当前状态: {}", currentStatus);
            return currentStatus;
        }
    }
}